/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * <p>Project: javase2203 - T19
 * <p>Powered by webrx On 2022-08-10 11:27:53
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class T19 {
    List<String> set = new ArrayList<>();
    ReentrantLock lo = new ReentrantLock(true);
    int num = 50;

    public T19() {
        this.num = 50;
        for (int i = 0; i < this.num; i++) {
            set.add(String.format("%03d", i + 1));
        }
    }

    public T19(int num) {
        this.num = num;
        for (int i = 0; i < this.num; i++) {
            set.add(String.format("%03d", i + 1));
        }
    }

    public void out() {
        Random rand = new Random();
        String t = Thread.currentThread().getName();
        while (this.set.size() > 0) {
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            //lo.lock();
            synchronized (this) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    int index = rand.nextInt(this.set.size());
                    String p = this.set.get(index);
                    this.set.remove(p);
                    if (this.set.size() == 0) {
                        System.out.printf("%s：售出%s票，票已经售完。%n%n", t, p);
                    } else {
                        System.out.printf("%s：售出%s票，还有%d张票%n", t, p, this.set.size());
                    }
                } catch (Exception e) {
                    System.out.printf("%s：票已经售完。%n", t);
                }
            }
            //lo.unlock();
        }
    }

    public static void main(String[] args) {
        T19 t = new T19(12);
        new Thread(t::out, "　东风路").start();
        new Thread(t::out, "　南阳路").start();
        new Thread(t::out, "　瑞达路").start();
        new Thread(t::out, "科学大道").start();
    }
}
